<template>
  <div class="update_WX_scenario">
    <el-form ref="formRef" :model="formData" label-width="160px" v-if="loaded">
      <!-- 微信客服账号 -->
      <el-form-item :label="$t('configLazyLoad.channel.WXOfficial011')" props="corpid">
        <el-select v-model="formData.corpid" :placeholder="$t('public.pleasePick')" :disabled="formData._id ? true : false" @change="authorizationChange">
          <el-option
            v-for="item in authorizationArr"
            :key="item.corpid"
            :label="item.corpName"
            :value="item.corpid"
          ></el-option>
        </el-select>
      </el-form-item>
      <!-- 接入号名称 -->
      <el-form-item :label="$t('configLazyLoad.channel.WXOfficial012')" props="name"> 
        <el-input v-model="formData.name" :placeholder="$t('public.pleaseInput')"></el-input>
      </el-form-item>
      <!-- 客服账号 -->
      <el-form-item :label="$t('configLazyLoad.channel.custAccount')" props="openKfid">
        <el-select v-model="formData.openKfid" :placeholder="$t('public.pleasePick')" :disabled="formData._id ? true : false">
          <el-option
            v-for="item in customerArr"
            :key="item.open_kfid"
            :label="item.name"
            :value="item.open_kfid"
          ></el-option>
        </el-select>
      </el-form-item>
      <!-- 消息分发技能组 -->
      <el-form-item :label="$t('configLazyLoad.interfaceConfig.msgGroup')" prop="to_peer">
        <el-select size="mini" v-model.trim="formData.to_peer" :placeholder="$t('public.pleasePick')" @change="topeerChang">
          <el-option
            v-for="item in peerOptions"
            :key="item.Exten"
            :label="item.DisplayName"
            :value="item.Exten"
          >
          </el-option>
        </el-select>
      </el-form-item>
      <!-- 启用智能机器人 -->
      <el-form-item :label="$t('config.channel.isUseRobt')" prop="robot">
        <el-select size="mini" v-model.trim="formData.robot" :placeholder="$t('public.pleasePick')" @visible-change="robotSelectShow">
          <el-option value="">{{$t('public.pleasePick')}}</el-option>
          <el-option
            v-for="item in robotOptions"
            :key="item._id"
            :label="item.robot_name_new"
            :disabled="item.disabled"
            :value="item._id">
          </el-option>
        </el-select>
      </el-form-item>
      <!-- 机器人辅助座席   不启用日程并且有辅助座席的数据的时候才会展示 -->
      <el-form-item v-show="aiRobots.length > 0"  :label="$t('configLazyLoad.channel.robotAssistId')" prop="robotAssistId">
        <el-select size="small" v-model.trim="formData.robotAssistId" :placeholder="$t('public.pleasePick')" @visible-change="robotSelectShow">
          <el-option value="">{{$t('public.pleasePick')}}</el-option>
          <el-option
            v-for="item in aiRobots"
            :key="item._id"
            :label="item.robot_name_new"
            :disabled="item.disabled"
            :value="item._id">
          </el-option>
        </el-select>
      </el-form-item>
      <!-- 是否开启触发词命中转人工 -->
      <el-form-item :label="$t('configLazyLoad.channel.turnTip3')" prop="openTriggerWord">
        <el-radio-group v-model.trim="formData.openTriggerWord">
          <el-radio :label="true">{{$t('public.yes')}}</el-radio>
          <el-radio :label="false">{{$t('public.no')}}</el-radio>
        </el-radio-group>
        <question-tooltip
                class="wechatTootip"
                :direction="'bottom'"
                :tipContent="$t('configLazyLoad.channel.turnTip4')">
        </question-tooltip>
      </el-form-item>
      <!-- 转人工触发词 -->
      <el-form-item :label="$t('config.channel.userPeopleWord')" prop="convert_words">
        <el-input size="mini" v-model.trim="formData.convert_words" :placeholder="$t('configLazyLoad.channel.turnTip5')"></el-input>
        <question-tooltip
                class="wechatTootip"
                :direction="'bottom'"
                :tipContent="$t('configLazyLoad.channel.turnTip6')">
        </question-tooltip>
      </el-form-item>
      <!-- 欢迎语推送时机 -->
      <el-form-item :label="$t('config.channel.sendWelcomeMsg')" prop="welcomePushTime" style="text-align: left">
        <el-radio-group v-model="formData.welcomePushTime" @change="pushTimeChange">
          <el-radio class="radio" label="access">{{$t('config.channel.enterSystem')}}</el-radio>
          <el-radio class="radio welcome-radio" label="claim">{{$t('config.channel.collectSeats')}}</el-radio>
        </el-radio-group>
      </el-form-item>
      <!-- 欢迎语 -->
      <el-form-item :label="$t('config.channel.welcomeMsg')" prop="welcome_msg">
        <span class="remark">{{$t('configLazyLoad.channel.webStyleTip5')}}</span>
        <question-tooltip
          class="wechatTootip"
          :direction="'bottom'"
          :tipContent="$t('configLazyLoad.channel.webStyleTip6')">
        </question-tooltip>
        <div class="placeholder_box">
          <dl 
            v-for="(place, index) in placeholderArr" 
            :key="index" 
            @click="addPlaceholder(place.data)" 
            :title="place.content">
            {{place.content}}
            <i class="iconfont icon-zhankai"></i>
          </dl>
        </div>
        <el-input size="mini" type="textarea" v-model="formData.welcome_msg"></el-input>
      </el-form-item>
      <!-- 是否启用满意度评价 -->
      <el-form-item :label="$t('config.channel.isUseSatisfaction')" prop="webchat_csr" style="text-align: left">
        <el-radio class="radio statis-radio" v-model.trim="formData.webchat_csr" :label="true">{{$t('config.channel.enabled')}}</el-radio>
        <el-radio class="radio" v-model.trim="formData.webchat_csr" :label="false">{{$t('config.channel.notEnabled')}}</el-radio>
      </el-form-item>
      <div style="margin: 20px">
        <el-button type="primary" class="primary_btn" @click="submit">{{$t('public.confirm')}}</el-button>
      </div>
    </el-form>
  </div>
</template>
<script>
import { deepClone } from '@/utils/m7Utils'
import questionTooltip from '@/components/ui-modules/questionToolTip/QuestionToolTip.vue'
export default {
  name: "updateWXScenario",
  data () {
    return {
      formData: {
        corpid: '',
        corpName: '',
        name: '',
        platform: 'wxkf',
        openKfid: '',
        to_peer: '',
        robot: '',
        robotName: '',
        robotAssistId: '',
        robotAssistName: '',
        openTriggerWord: true,
        convert_words: '',
        welcomePushTime: 'access',
        welcome_msg: '',
        webchat_csr: false
      },
      loaded: false,
      authorizationArr: [],     // 微信客服账号列表
      customerArr: [],          // 客服账号列表
      peerOptions: [],  //  技能组列表
      robotOptions: [], //  机器人列表
      aiRobots: [],     //  机器人辅助座席列表
      placeholderArr: [ //  欢迎语占位符
        {
          content: this.$t('configLazyLoad.channel.nickName'),
          data: 'nickName'
        }
      ]
    }
  },
  components: {
    questionTooltip
  },
  props: {
    data: {
      type: Object,
      default: function () {
        return {}
      }
    }
  },
  methods: {
    submit() {
      let data = deepClone(this.formData)
      if (this.peerOptions.length === 0) {
        this.$message.error(this.$t('configLazyLoad.channel.WXOfficial013'))
        return
      }
      if (!data.corpid) {
        this.$message.error(this.$t('configLazyLoad.channel.WXOfficial014'))
        return
      }
      if (!data.name) {
        this.$message.error(this.$t('configLazyLoad.channel.WXOfficial015'))
        return
      }
      if (!data.openKfid) {
        this.$message.error(this.$t('configLazyLoad.channel.WXOfficial016'))
        return
      }
      if (!data.to_peer) {
        this.$message.error(this.$t('webchat.placeSkillsGrouop'))
        return
      }
      
      if (data.robot === '') {
        data.robotType = ''
        data.robotName = ''
      } else {
        let that = this
        console.log(that.robotOptions)
        this.robotOptions.forEach((item) => {
          if (item._id === data.robot) {
            if (item.Nick) {
              this.$set(data, 'robotType', item.robotType)
            } else {
              this.$set(data, 'robotType', item.robot_type_new)  
            }
            this.$set(data, 'robotName', item.robot_name_new)
          }
        })
      }
      //          机器人辅助座席，增加assistRobotType参数
      if (data.robotAssistId) {
        this.aiRobots.map((item) => {
          if (data.robotAssistId === item._id) {
            if (data.robotAssistId !== '') {
              this.$set(data, 'assistRobotType', item.robotType)
              this.$set(data, 'robotAssistName', item.name)
            } else {
              this.$set(data, 'assistRobotType', '')
              this.$set(data, 'robotAssistName', '')
            }
          }
        })
      } else {
        data.assistRobotType = ''
        data.robotAssistName = ''
      }
      var action = 'saveWxkfConfig'
      if (data._id) {
        action = 'updateWxkfConfig'
      }
      this.$store.dispatch(action, data).then(req => {
        if (req && req.success) {
          this.$message.success(this.$t('config.channel.saveSuccess'))
          this.$emit('back')
        }
      })
    },
    authorizationChange (data) {
      console.log(data)
      console.log(this.authorizationArr)
      this.authorizationArr.forEach(item => {
        if (item.corpid === data) {
          this.customerArr = deepClone(item.kfAccountList)
          this.$set(this.formData, 'corpName', item.corpName)
        }
      })
    },
    // openKfIdChange (data) {
    //   this.customerArr.forEach(item => {
    //     if (item.open_kfid === data) {
    //       this.$set(this.formData, 'openKfName', item.name)
    //     }
    //   })
    // },
    topeerChang (data) {
      this.peerOptions.forEach(item => {
        if (data === item.Exten) {
          this.$set(this.formData, 'to_peer_name', item.DisplayName)
        }
      })
    },
    //  机器人&&智能机器人的select下拉框出现时获取机器人列表
    robotSelectShow (show) {
      if (show) {
        this.$store.dispatch('queryM7AIRobot', {}).then((res2) => {
          if (res2 && res2.success && res2.data && res2.data.length > 0) {
            let aiRobot = res2.data
            let allRobot = this.robotOptions
            aiRobot.forEach((item1) => {
              item1._id = item1.Id
              item1.robot_name_new = item1.Nick
              let exist = allRobot.findIndex((all) => {
                return all.Id === item1.Id
              })
              if (exist === undefined) {
                allRobot.push(item1)
              } else {
                allRobot.splice(exist, 1, item1)
              }
            })
            this.aiRobots = aiRobot
            this.robotOptions = allRobot
          }
        })
      }
    },
    //  更改欢迎语推送时机，改变欢迎语占位符展示
    pushTimeChange (data) {
      if (data === 'access') {
        this.placeholderArr = [
          {
            content: this.$t('configLazyLoad.channel.nickName'),
            data: 'nickName'
          }
        ]
        let str = ''
        if (this.formData.welcome_msg) {
          str = deepClone(this.formData.welcome_msg)
        }
        str = str.replace(/\{agent\}/g, '')
        str = str.replace(/\{agentName\}/g, '')
        this.formData.welcome_msg = str
      } else if (data === 'claim') {
        this.placeholderArr = [
          {
            content: this.$t('configLazyLoad.channel.nickName'),
            data: 'nickName'
          }, {
            content: this.$t('configLazyLoad.channel.agent'),
            data: 'agent'
          }, {
            content: this.$t('configLazyLoad.channel.agentName'),
            data: 'agentName'
          }, {
            content: this.$t('configLazyLoad.channel.agentNickName'),
            data: 'agentNickName'
          }, {
            content: this.$t('configLazyLoad.channel.agentPhone'),
            data: 'agentPhone'
          }
        ]
      }
    },
    //  点击添加欢迎语
    addPlaceholder (msg) {
      this.formData.welcome_msg += '{' + msg + '}'
    },
    fetchData () {
      if (this.data._id) {
        this.formData = deepClone(this.data)
        this.authorizationChange(this.formData.corpid)
        this.pushTimeChange(this.formData.welcomePushTime)
        var kfidFlag = false
        this.customerArr.forEach((item) => {
          if (item.open_kfid === this.formData.openKfid) {
            kfidFlag = true
          }
        })
        if (!kfidFlag) {
          this.$set(this.formData, 'openKfid', '')
        }
      }
      this.loaded = true
    }
  },
  beforeMount () {
    //      获取技能组列表
    Promise.all([
      this.$store.dispatch('getCache', { type: 'mailQueues' }),
      this.$store.dispatch('getCache', { type: 'robotConfig' }),
      this.$store.dispatch('getWxkfWorkConfigs', {})
    ]).then(([queues, robot, authorization]) => {
      let mailQueues = this.$getCache('mailQueues')
      if (!mailQueues || mailQueues.length === 0) {
        this.peerOptions = []
      } else {
        this.peerOptions = mailQueues
      }

      let robotConfig = this.$getCache('robotConfig')
      this.robotOptions = robotConfig || []
      this.$store.dispatch('queryM7AIRobot', {}).then((res2) => {
        if (res2 && res2.success && res2.data && res2.data.length > 0) {
          let aiRobot = res2.data
          aiRobot.forEach((item1) => {
            item1._id = item1.Id
            item1.robot_name_new = item1.Nick
          })
          this.aiRobots = aiRobot
          let configArr = []
          this.robotOptions.forEach((config) => {
            if (config.robot_type !== 'didi') {
              configArr.push(config)
            }
          })
          this.robotOptions = configArr.concat(this.aiRobots)
          console.log(this.robotOptions)
        }
      })
      this.authorizationArr = deepClone(authorization.list)
      this.fetchData()
    })
  }
  
}
</script>
<style scope lang="stylus">
  @import "../../../../../assets/common.styl"
  .update_WX_scenario
    width 460px
    margin 10px auto 0
    .el-form-item .el-form-item__content
      text-align left
    .el-select
      width 100%
    .wechatTootip
      position absolute
      right -25px
    .remark
      color #3b5998
      font-size 12px
      .tip
        cursor pointer
        display inline-block
        height 16px
        width 16px
        border 1px solid $c-main
        text-align center
        line-height 16px
        border-radius 50%
        margin-left 2px
        .iconfont
          font-size 10px
          color $c-main
    .placeholder_box
      margin-top 10px
      font-size 12px
      line-height:16px
      dl
        border 1px solid $c-main
        color $c-main
        border-radius 6px
        display inline-block
        padding 4px
        margin 0 10px 10px 0
        cursor pointer
      .iconfont
        font-size 12px
</style>